/**
 *Copyright: Copyright (c) 2015
 */
package com.tyjw.common;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;

/**
 * @author wenghongbo
 *
 * 2015年8月4日下午5:32:18
 */
public class HttpUtils {

	
	private static HttpClient client;
	
	
	public static String httpGet(String url,Map<String,String> headMap){  
		String result = null;
        try {
			if(client==null) {
				client=httpClient();
			}
        	HttpGet httpGet = new HttpGet(url);
        	
        	if(headMap!=null){
	            for(String key:headMap.keySet()){
	            	httpGet.setHeader(key, headMap.get(key));
	            }
        	}
            HttpResponse response = client.execute(httpGet);  
            if(response != null){  
                HttpEntity resEntity = response.getEntity();  
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity,"utf-8");  
                }  
            } 
        }catch(Exception e){
        	e.printStackTrace();
        }
        return result;  
    }
	
	
	public static byte[] httpGet(String url){  
		//System.out.println(url);
        try {
			if(client==null) {
				client=httpClient();
			}
        	HttpGet httpGet = new HttpGet(url);
        	
            HttpResponse response = client.execute(httpGet);  
            if(response != null){  
                HttpEntity resEntity = response.getEntity();  
                if(resEntity != null){
                   return EntityUtils.toByteArray(resEntity);  
                }  
            } 
        }catch(Exception e){
        	e.printStackTrace();
        }
        return null;  
    }
	
	
	public static String httpPost(String url,String data,Map<String,String> headMap){
		try{
			if(client==null) {
				client=httpClient();
			}
			StringBuilder rdata=new StringBuilder();
            HttpPost post = new HttpPost(url);
            if(headMap!=null && headMap.size()>0){
	            for(String key:headMap.keySet()){
	            	post.setHeader(key, headMap.get(key));
	            }
            }
            StringEntity reqEntity = new StringEntity(data,"UTF-8");
            reqEntity.setContentType("application/json; charset=utf-8");
            Header header=new BasicHeader("accept-encoding","gzip");
            reqEntity.setContentEncoding(header);
            reqEntity.setContentEncoding("UTF-8");
            post.setEntity(reqEntity);
            HttpResponse response = client.execute(post);  
            HttpEntity entity = response.getEntity();
            if(entity != null) {
            	 BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(),"UTF-8"));
                 String line=null;
                 while((line=reader.readLine())!=null){
                	 rdata.append(line.trim());
                 }
            	 reader.close();
            }
            return rdata.toString();
		}catch(Exception e){
			//e.printStackTrace();
			return null;
		}
	}
	
	private static  HttpClient httpClient() {
	    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
	            .register("http", PlainConnectionSocketFactory.getSocketFactory())
	            .register("https", SSLConnectionSocketFactory.getSocketFactory())
	            .build();
		RequestConfig requestConfig = RequestConfig.custom().
                setConnectTimeout(10000).setConnectionRequestTimeout(20000)
                .setSocketTimeout(10000).setRedirectsEnabled(true).build();
	    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
	    connectionManager.setMaxTotal(20);
	    connectionManager.setDefaultMaxPerRoute(5);
	    return HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).setConnectionManager(connectionManager).build();
	}
}
